package com.yanqu.road.web.controller.usercenter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.impl.admin.AdminCommonDaoImpl;
import com.yanqu.road.dao.impl.admin.AdminCommonDaoImpl2;
import com.yanqu.road.dao.impl.servercenter.PlatformGoodsDaoImpl;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.entity.admin.AdminResult2;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.servercenter.PlatformPolicy;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.controller.usercenter.newadmin.CenterReloadHelper;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/usercenter/admin")
public class CenterOtherAdminController {

    /**
     *  6.1 政策协议新增
     */
    @ResponseBody
    @RequestMapping(value = "addPolicy", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String addPolicy(HttpServletRequest request, @RequestBody String json){

        if(StringUtils.isNullOrEmpty(json)){
            return AdminResult.failMsg("请求参数空").toJsonString();
        }

        JSONObject jsonObject = JSONObject.parseObject(json);

        int channelId = jsonObject.getIntValue("channelId");

        int status = jsonObject.getIntValue("status");

        PlatformPolicy platformPolicy = new PlatformPolicy();
        platformPolicy.setChannelId(channelId);
        if(status == 1){
            String userAgreement = jsonObject.getString("userAgreement");
            String privacyPolicy = jsonObject.getString("privacyPolicy");
            platformPolicy.setUserAgreement(userAgreement);
            platformPolicy.setPrivacyPolicy(privacyPolicy);
        }else {
            platformPolicy.setUserAgreement("");
            platformPolicy.setPrivacyPolicy("");
        }

        boolean result = new AdminCommonDaoImpl().updatePlatformPolicy(platformPolicy);
        if(!result){
            return AdminResult.failMsg("失败").toJsonString();
        }
        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     *  9.1 新增/修改宝箱 (t_s_platform_goods)
     */
    @ResponseBody
    @RequestMapping(value = "updatePlatformGoods", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String updatePlatformGoods(HttpServletRequest request, @RequestBody JSONObject jsonObject) {


        int channelId = jsonObject.getIntValue("channelId");

        //宝箱id
        int boxId = 0;

        if(jsonObject.containsKey("boxId")) {
            boxId = jsonObject.getIntValue("boxId");
            if(boxId < 0){
                return AdminResult.failMsg("boxId 无效参数").toJsonString();
            }
        }

        int gameType = 0;
        if(jsonObject.containsKey("gameType")) {
            gameType = jsonObject.getIntValue("gameType");
        }

        //解析参数
        Map<String, Object> params = new HashMap<>();

        params.put("gameType", gameType);

        int batchUse = jsonObject.getIntValue("batchUse");
        int freezeFlag = jsonObject.getIntValue("freezeFlag");

        params.put("type", 7);//固定，平台宝箱
        params.put("params", "0|0|0|0");//固定
        params.put("channelId", channelId);

        int quality = jsonObject.getIntValue("quality");
        params.put("quality", quality);

        String icon = jsonObject.getString("icon");
        params.put("icon", icon);

        String props = jsonObject.getString("props").replace("|", ";");
        params.put("extendParam", props);

        //邮件多语言
        JSONArray contentArray = jsonObject.getJSONArray("list");

        //目前取第一个
        JSONObject contentObject = contentArray.getJSONObject(0);

        String mailTitle = contentObject.getString("mailTitle");
        params.put("mailTitle", mailTitle);

        String mailContent = contentObject.getString("mailContent");
        params.put("mailContent", mailContent);

        String chestName = contentObject.getString("chestName");
        params.put("name", chestName);

        String chestDescription = contentObject.getString("chestDescription");
        params.put("desc", chestDescription);

        params.put("canUse", batchUse);
        params.put("canBagUse", freezeFlag == 1 ? 0 : 1);

        if(boxId == 0) {
            //新增宝箱
            int platformMaxGoodsId = new AdminCommonDaoImpl().getPlatformMaxGoodsId(channelId);
            if (platformMaxGoodsId == 0) {
                if(channelId == 0){
                    platformMaxGoodsId = 1000001001;
                }else {
                    platformMaxGoodsId = channelId * 1000000;
                }
            }
            params.put("id", platformMaxGoodsId + 1);
        }else {
            params.put("id", boxId);
        }

        boolean result;

        //多语言
        List<Map<String, Object>> languageList = new ArrayList<>();
        if(contentArray.size() > 0){
            for (int i = 0; i < contentArray.size(); i++) {
                JSONObject langObj = contentArray.getJSONObject(i);

                if(langObj.containsKey("mailTitle") && langObj.get("mailTitle") != null){
                    Map<String, Object> titilMap = new HashMap<>();
                    titilMap.put("key", mailTitle);
                    titilMap.put("language", langObj.get("languageKey"));
                    titilMap.put("content", langObj.get("mailTitle"));
                    titilMap.put("channelId", channelId);
                    titilMap.put("type", 4);
                    titilMap.put("f_id", params.get("id"));
                    languageList.add(titilMap);
                }

                if(langObj.containsKey("mailContent") && langObj.get("mailContent") != null){
                    Map<String, Object> contentMap = new HashMap<>();
                    contentMap.put("key", mailContent);
                    contentMap.put("language", langObj.get("languageKey"));
                    contentMap.put("content", langObj.get("mailContent"));
                    contentMap.put("channelId", channelId);
                    contentMap.put("type", 4);
                    contentMap.put("f_id", params.get("id"));
                    languageList.add(contentMap);
                }

                if(langObj.containsKey("chestName") && langObj.get("chestName") != null){
                    Map<String, Object> nameMap = new HashMap<>();
                    nameMap.put("key", chestName);
                    nameMap.put("language", langObj.get("languageKey"));
                    nameMap.put("content", langObj.get("chestName"));
                    nameMap.put("channelId", channelId);
                    nameMap.put("type", 4);
                    nameMap.put("f_id", params.get("id"));
                    languageList.add(nameMap);
                }

                if(langObj.containsKey("chestDescription") && langObj.get("chestDescription") != null){
                    Map<String, Object> descMap = new HashMap<>();
                    descMap.put("key", chestDescription);
                    descMap.put("language", langObj.get("languageKey"));
                    descMap.put("content", langObj.get("chestDescription"));
                    descMap.put("channelId", channelId);
                    descMap.put("type", 4);
                    descMap.put("f_id", params.get("id"));
                    languageList.add(descMap);
                }
            }
        }

        //以下看不懂了吧
        if(boxId == 0){
            //后台没传，视为新增
            result = new AdminCommonDaoImpl().insertPlatformGoods(params);
            //删除旧语言，不管是否成功
            new AdminCommonDaoImpl().deleteChannelBrocadeBoxLanguage("" + params.get("id"), channelId);
            if(!languageList.isEmpty()){
                //如果有多语言，则新增多语言
                result = result && new AdminCommonDaoImpl().batchUpdateChannelLanguage(languageList, channelId);
            }
        }else {
            //后台有传boxId,查库看下是否存在，复杂了吧
            Map<String, Object> goods = new AdminCommonDaoImpl().getPlatformGoods(channelId, boxId);
            if(goods.isEmpty()){
                //库里没有，则新增
                result = new AdminCommonDaoImpl().insertPlatformGoods(params);
                //删除旧语言，不管是否成功
                new AdminCommonDaoImpl().deleteChannelBrocadeBoxLanguage("" + params.get("id"), channelId);
                if(!languageList.isEmpty()){
                    //如果有多语言，则新增多语言
                    result = result && new AdminCommonDaoImpl().batchUpdateChannelLanguage(languageList, channelId);
                }
            }else {
                //后台传了boxId,库里有则视为更新
                //更新下id
                params.put("id", goods.get("id"));
                //更新
                result = new AdminCommonDaoImpl().updatePlatformGoods(params);
                if(!languageList.isEmpty()){
                    //删除旧语言，不管是否成功
                    new AdminCommonDaoImpl().deleteChannelBrocadeBoxLanguage("" + params.get("id"), channelId);
                    //更新下多语言 对应的f_id
                    for (Map<String, Object> objectMap : languageList) {
                        objectMap.put("f_id", params.get("id"));
                    }
                    //新增多语言
                    result = result && new AdminCommonDaoImpl().batchUpdateChannelLanguage(languageList, channelId);
                }
            }
        }
        if(!result){
            return AdminResult.failMsg("失败").toJsonString();
        }


        AdminResult result1 = AdminResult.defaultInstance();
        result1.getData().put("boxId", params.get("id"));


        //说是要直接刷新
        List<ServerInfo> openServerList = ServerListMgr.getOpenServerList(channelId);
        String msg = "操作成功.";
        msg += CenterReloadHelper.serverMgrReload(openServerList, "PlatformGoodsMgr", 20);
        msg += CenterReloadHelper.serverMgrReload(openServerList, "ServerLanguageMgr", 20);
        result1.setMsg(msg);
        return result1.toJsonString();
    }

    /**
     *  9.2 删除宝箱
     */
    @ResponseBody
    @RequestMapping(value = "deletePlatformGoods", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String deletePlatformGoods(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");
        int boxId = jsonObject.getIntValue("boxId");

        boolean result = new AdminCommonDaoImpl().deletePlatformGoods(channelId, boxId);

        if(!result){
            return AdminResult.failMsg("删除失败").toJsonString();
        }

        return AdminResult.defaultInstance().toJsonString();
    }


    /**
     *  9.3 宝箱查询（默认按照宝箱ID降序排序）
     */
    @ResponseBody
    @RequestMapping(value = "searchPlatformGoods", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String searchPlatformGoods(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");

        int pageNum = jsonObject.getIntValue("pageNum");

        int pageSize = jsonObject.getIntValue("pageSize");

        int boxId = 0;
        if(jsonObject.containsKey("boxId")){
            boxId = jsonObject.getIntValue("boxId");
        }

        //品质
        int quality = 0;
        if(jsonObject.containsKey("quality")){
            quality = jsonObject.getIntValue("quality");
        }
        //图标
        String icon = "";
        if(jsonObject.containsKey("icon")){
            icon = jsonObject.getString("icon");
        }
        //宝箱名称
        String chestName = "";
        if(jsonObject.containsKey("chestName")){
            chestName = jsonObject.getString("chestName");
        }


        Map<Integer, GoodsInfo> goodsInfoMap = new PlatformGoodsDaoImpl().getGoodsInfoMap(channelId);
        List<GoodsInfo> list = new ArrayList<>();
        for (GoodsInfo goodsInfo : goodsInfoMap.values()) {
            if(boxId > 0 && goodsInfo.getGoodsId() != boxId){
                continue;
            }
            if(quality > 0 && goodsInfo.getQuality() != quality){
                continue;
            }
            if(!StringUtils.isNullOrEmpty(icon)){
                if(!goodsInfo.getIcon().contains(icon)){
                    continue;
                }
            }
            if(!StringUtils.isNullOrEmpty(chestName)){
                if(!goodsInfo.getGoodsName().contains(chestName)){
                    continue;
                }
            }

            list.add(goodsInfo);
        }
        list.sort(Comparator.comparingInt(GoodsInfo::getGoodsId));

        AdminResult result = AdminResult.defaultInstance();

        result.getData().put("total", list.size());

        List<JSONObject> row = new ArrayList<>();
        //分页结果
        int startIndex = (pageNum - 1) * pageSize;
        startIndex = Math.max(0, startIndex);

        for (int i = startIndex; i < startIndex + pageSize && i < list.size(); i++) {
            GoodsInfo goodsInfo = list.get(i);
            JSONObject obj = new JSONObject();
            obj.put("channelId", channelId);
            obj.put("boxId", goodsInfo.getGoodsId());
            obj.put("quality", goodsInfo.getQuality());
            obj.put("icon", goodsInfo.getIcon());
            obj.put("props", goodsInfo.getExtendParam());
            obj.put("batchUse", goodsInfo.getCanUse());
            obj.put("freezeFlag", 0);
            row.add(obj);
        }
        result.getData().put("row", row);

        return result.toJsonString();
    }


    /**
     * 46.1 新增大区配置
     */
    @ResponseBody
    @RequestMapping(value = "channelParamsAdd", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String channelParamsAdd(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        int channelId = jsonObject.getIntValue("channelId");
        String param = jsonObject.getString("param");
        String value = jsonObject.getString("value");
        String remark = jsonObject.getString("remark");

        boolean b = new AdminCommonDaoImpl2().repeatedChannelParams(channelId, param);
        if(b){
            return AdminResult.failCode(-1, "添加失败，已经存在该配置").toJsonString();
        }

        int maxId = new AdminCommonDaoImpl().getChannelConfigMaxId();

        boolean success = new AdminCommonDaoImpl().addChannelConfig(++maxId, channelId, param, value, remark);

        AdminResult result = AdminResult.defaultInstance();
        if(!success){
            result.setCode(-1);
        }
        return result.toJsonString();
    }

    /**
     * 46.2 修改大区配置
     */
    @ResponseBody
    @RequestMapping(value = "channelParamsUpdate", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String channelParamsUpdate(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        int channelId = jsonObject.getIntValue("channelId");
        String param = jsonObject.getString("param");
        String value = jsonObject.getString("value");
        String remark = jsonObject.getString("remark");

        boolean success = new AdminCommonDaoImpl().updateChannelConfig(channelId, param, value, remark);

        AdminResult result = AdminResult.defaultInstance();
        if(!success){
            result.setCode(-1);
        }
        return result.toJsonString();
    }


    /**
     * 46.3 删除大区配置
     */
    @ResponseBody
    @RequestMapping(value = "channelParamsDel", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String channelParamsDel(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        int channelId = jsonObject.getIntValue("channelId");
        String param = jsonObject.getString("param");

        boolean success = new AdminCommonDaoImpl().deleteChannelConfig(channelId, param);

        AdminResult result = AdminResult.defaultInstance();
        if(!success){
            result.setCode(-1);
        }
        return result.toJsonString();
    }


    /**
     * 46.4 刷新大区配置
     */
    @ResponseBody
    @RequestMapping(value = "channelParamsRefresh", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String channelParamsRefresh(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        int channelId = jsonObject.getIntValue("channelId");


        AdminResult2 result = new AdminResult2();

        try {
            new ServerListMgr().reload();
        } catch (Exception e) {
            ServerListMgr.getLogger().error("", e);
        }

        //刷新区服
        List<ServerInfo> channelServerList = ServerListMgr.getChannelServerList(channelId);

        String msg = CenterReloadHelper.serverMgrReload(channelServerList, "ChannelConfigMgr", 30);
        result.setMsg(msg);

        return result.toJsonString();
    }

    /**
     * 46.5 渠道大区查询
     */
    @ResponseBody
    @RequestMapping(value = "channelParamsList", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String channelParamsList(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        int channelId = jsonObject.getIntValue("channelId");


        AdminResult2 result2 = AdminResult2.defaultInstance();

        List<HashMap<String, Object>> channelConfig = new AdminCommonDaoImpl().getChannelConfig(channelId);

        result2.getData().addAll(channelConfig);

        return result2.toJsonString();
    }

}
